package dao_sys

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_sys"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetDictTypePageList(sysDictType model_sys.SelectSysDictType) (sysDictTypes []model_sys.SysDictTypeVo, total int64, err error) {
	db := mysql.Db().Model(&model_sys.SysDictTypePo{})
	if sysDictType.DictName != "" {
		db = db.Where("dict_name like ?", "%"+sysDictType.DictName+"%")
	}
	if sysDictType.DictType != "" {
		db = db.Where("dict_type like ?", "%"+sysDictType.DictType+"%")
	}
	if sysDictType.Status != "" {
		db = db.Where("status = ?", sysDictType.Status)
	}
	if !sysDictType.StartTime.IsZero() {
		db = db.Where("create_time >= ?", sysDictType.StartTime)
	}
	if !sysDictType.EndTime.IsZero() {
		db = db.Where("create_time <= ?", sysDictType.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("create_time desc")
	if sysDictType.PageNum != nil && sysDictType.PageSize != nil {
		db = db.Limit(*sysDictType.PageSize).Offset((*sysDictType.PageNum - 1) * *sysDictType.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = db.Find(&sysDictTypes).Error
	err = errs.ErrNotFound(err)
	return
}

func GetDictTypeById(dictId int) (sysDictType model_sys.SysDictTypeVo, err error) {
	db := mysql.Db().Model(&model_sys.SysDictTypePo{})
	err = db.Where("dict_id = ? and deleted = '0'", dictId).First(&sysDictType).Error
	err = errs.ErrNotFound(err)
	return
}

func AddDictType(sysDictType model_sys.SysDictTypePo) (int, error) {
	err := mysql.Db().Create(&sysDictType).Error
	return sysDictType.DictId, errs.ErrNotFound(err)
}

func EditDictType(sysDictType model_sys.SysDictTypePo) (int64, error) {
	res := mysql.Db().Updates(&sysDictType)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveDictType(dictIds []string, uk string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysDictTypePo{})
	db.Where("dict_id in (?)", dictIds)
	res := db.Updates(&model_sys.SysDictTypePo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeleteDictType(dictIds []string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysDictTypePo{})
	res := db.Delete(&model_sys.SysDictTypePo{}, dictIds)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}
